import datetime
import json
import os
import sys

import matplotlib.pyplot as plt
import mpl_finance as mpf
from matplotlib.pylab import date2num

base_path = os.path.split(os.path.realpath(__file__))[0]
father_path = os.path.abspath(os.path.dirname(os.getcwd()) + os.path.sep + ".")
sys.path.append(father_path)
from utils import k_util, ave_util, price_util, select_util
from common.enums.Enums import Stock
from service.data_service import stock_dict


def day_k_chat(code, size):
    day_k_with_path(code, size, father_path + "\\view\\pic\\")
    # plt.show()


def day_k_with_path(code, size, save_path):
    quotes = []
    k_dict = k_util.day_k_local(code, size)
    # print(k_dict)
    for json_str in k_dict:
        s_json = json.loads(str(json_str).replace('\'', '\"'))
        sdate = str(s_json[Stock.rq.value])  # 注意：loc返回数值，iloc返回dataframe 行列
        sdate_num = date2num(datetime.datetime.strptime(sdate, '%Y-%m-%d'))  # 日期需要特定形式，这里进行转换
        sdate_plt = sdate_num
        sopen = float(s_json[Stock.kp.value])
        shigh = float(s_json[Stock.max.value])
        slow = float(s_json[Stock.min.value])
        sclose = float(s_json[Stock.sp.value])
        datas = (sdate_plt, sopen, shigh, slow, sclose)  # 按照 candlestick_ohlc 要求的数据结构准备数据
        quotes.append(datas)
    fig, ax = plt.subplots(facecolor=(0, 0.3, 0.5), figsize=(12, 8))
    fig.subplots_adjust(bottom=0.1)
    ax.xaxis_date()
    plt.xticks(rotation=45)  # 日期显示的旋转角度
    plt.title('600000')
    plt.xlabel('time')
    plt.ylabel('price')
    # 上涨为红色K线，下跌为绿色，K线宽度为0.7
    mpf.candlestick_ohlc(ax, quotes, width=0.7, colorup='r', colordown='green')
    plt.grid(True)
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    if save_path[-1] != '\\':
        save_path = save_path + '\\'
    print("存储路径" + save_path + 'k_stock' + ".png")
    plt.savefig(save_path + code + '_k' + ".png", dpi=200)  # 保存图片
    # plt.show()
    plt.close()


def macd(stock, name):
    MACD_with_path(stock, name, base_path + "\\pic")


def MACD_with_path(stock, name, save_path):
    plt.figure(figsize=(12, 6), dpi=120)  # 调整图片比例，默认为640*480
    plt.rc('font', family='SimHei', size=10)  # 显示中文
    price_lines = price_util.get_rt_ps(stock, 10)
    klines = k_util.get_day_k(stock)
    MA5 = ave_util.five_ave_line_price(stock, klines)
    MA10 = ave_util.ave_line_price_n(stock, klines, 10)
    MA15 = ave_util.ave_line_price_n(stock, klines, 15)
    x_array = []
    price_array = []
    ma5_array = []
    ma10_array = []
    ma15_array = []
    for info_str in price_lines:
        infos = info_str.split(',')
        x_array.append(infos[0])
        price_array.append(float(infos[1]))
        ma5_array.append(MA5)
        ma10_array.append(MA10)
        ma15_array.append(MA15)
    import numpy as np
    x_axis = np.array(x_array)
    p_axis = np.array(price_array)
    ma5_axis = np.array(ma5_array)
    ma10_axis = np.array(ma10_array)
    ma15_axis = np.array(ma15_array)
    plt.title(str(stock) + ':' + str(name) + "--MACD折线图")
    plt.xlabel("时间轴")
    plt.ylabel("实时价格")
    # 以下为折线图
    plt.plot(x_axis, p_axis, "black", linestyle="-.", label="实时价格")  # 样式有：-,--,-.,:
    plt.plot(x_axis, ma5_axis, "r", linestyle="-", label="五日均线")
    plt.plot(x_axis, ma10_axis, "g", linestyle="-", label="十日均线")
    plt.plot(x_axis, ma15_axis, "y", linestyle="-", label="十五日线")
    # 折线图的表示结束
    plt.legend()  # 参数：loc="upper left"，默认为最优位置
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    if save_path[-1] != '\\':
        save_path = save_path + '\\'
    print("存储路径" + save_path + str(name) + ".png")
    plt.savefig(save_path + name + ".png", dpi=200)  # 保存图片
    # plt.show()
    plt.close()


def x_zhou():
    x_array = []
    date_time = datetime.datetime.now()
    for i in range(10):
        x_array.append((date_time - datetime.timedelta(minutes=i)).strftime("%H:%M"))

    print(x_array)


if __name__ == '__main__':
    print("折线图")
    # macd("601999", "出版传媒")
    s_dict = select_util.select_doc()
    for code in s_dict:
        print(code + "开始k")
        day_k_chat(code, 80)
        print(code + "结束k")
        print(code + "开始macd")
        macd(code, code + stock_dict[code]['name'] + 'macd')
        print(code + "结束macd")
